package org.xxpay.core.common.xss;

import org.xxpay.core.common.util.IPUtility;
import org.xxpay.core.common.util.MyLog;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * sql注入拦截过滤器
 */
public class SqlInjectionFilter implements Filter {

    private static final MyLog _log = MyLog.getLog(SqlInjectionFilter.class);
 
    public void destroy() {
        // TODO Auto-generated method stub
    }
     
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub
    }
     
    public void doFilter(ServletRequest args0, ServletResponse args1,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)args0;
        HttpServletResponse res=(HttpServletResponse)args1;
         //获得所有请求参数名
        Enumeration params = req.getParameterNames();
        String sql = "";
        while (params.hasMoreElements()) {
            //得到参数名
            String name = params.nextElement().toString();
            //得到参数对应值
            String[] value = req.getParameterValues(name);
            for (int i = 0; i < value.length; i++) {
                sql = sql + value[i];
            }
        }
        // 有sql关键字，跳转到error.html
        if (sqlValidate(sql)) {
            _log.info("sql拦截,ip:{}", IPUtility.getClientIp(req));
            throw new IOException("您发送请求中的参数中含有非法字符");
        } else {
            chain.doFilter(args0,args1);
        }
    }
     
    //效验
    protected static boolean sqlValidate(String str) {
        str = str.toLowerCase();//统一转为小写
        String badStr = "'|and |exec |insert |select |delete |update |count |master |truncate |declare |or ";//过滤掉的sql关键字，可以手动添加
        String[] badStrs = badStr.split("\\|");
        for (int i = 0; i < badStrs.length; i++) {
            if (str.indexOf(badStrs[i]) >= 0) {
                _log.info("sql拦截,非法字符:{}", badStrs[i]);
                return true;
            }
        }
        return false;
    }
}